package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.util.Jsons;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.atguigu.gmall.order.to.OrderMsgTo;
import com.atguigu.gmall.util.consts.MqConst;
import com.atguigu.gmall.util.service.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author:ahang
 * @create:2022-10-27 16:48
 * @Description:
 */
@Slf4j
@Service
public class CloseOrderListener {
    @Autowired
    OrderBizService orderBizService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitService rabbitService;

    @RabbitListener(queues = MqConst.ORDER_CLOSE_QUEUE)
    public void colseOrder(Message message, Channel channel) throws Exception {
        String json = new String(message.getBody());
        OrderMsgTo msgTo = Jsons.toObject(json, OrderMsgTo.class);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("订单消息抵达");
            orderBizService.closeOrder(msgTo.getOrderId(),msgTo.getUserId());
            //返回ack
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            rabbitService.retry(5,json,channel,deliveryTag);
        }

    }
}
